package com.moos.example;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.moos.example.adapter.CommentExpandAdapter;
import com.moos.example.bean.CommentBean;
import com.moos.example.bean.CommentDetailBean;
import com.moos.example.bean.DiscussDetailBean;
import com.moos.example.bean.ReplyDetailBean;
import com.moos.example.utils.HttpUtil;
import com.moos.example.view.CommentExpandableListView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DetailActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private CommentExpandableListView expandableListView;
    private CommentExpandAdapter adapter;
    CollapsingToolbarLayout collapsingToolbar;
    private List<CommentDetailBean> commentsList;
    private BottomSheetDialog dialog;

    private int key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        // 设置界面基础数据
        getDataFromIntent();
        initView();
    }

    /**
     * 设置跳转后的内容
     */
    private void getDataFromIntent() {
        Intent intent = getIntent();
        //从intent对象中把封装好的数据取出来
        String data = intent.getStringExtra("data");
        Gson gson = new Gson();
        DiscussDetailBean discussDetailBean = gson.fromJson(data, DiscussDetailBean.class);
        CircleImageView circleImageView = findViewById(R.id.detail_page_userLogo);
        TextView detail_page_userName = findViewById(R.id.detail_page_userName);
        TextView detail_page_time = findViewById(R.id.detail_page_time);
        TextView detail_page_title = findViewById(R.id.detail_page_title);
        TextView detail_page_story = findViewById(R.id.detail_page_story);
        detail_page_userName.setText(discussDetailBean.getNickName());
        detail_page_time.setText(discussDetailBean.getCreateDate());
        detail_page_title.setText(discussDetailBean.getTitle());
        detail_page_story.setText(discussDetailBean.getContent());


        Glide.with(this).load(discussDetailBean.getUserLogo())
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .error(R.drawable.user_other)
                .centerCrop()
                .into(circleImageView);

        key = discussDetailBean.getId();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        expandableListView = findViewById(R.id.detail_page_lv_comment);
        TextView bt_comment = findViewById(R.id.detail_page_do_comment);
        collapsingToolbar = findViewById(R.id.collapsing_toolbar);
        // 设置评论点击事件
        bt_comment.setOnClickListener(this);
        // 设置返回按钮
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        // 设置 toolbar
        collapsingToolbar.setTitle("详情");
        // 设置expandlistview
        requestData();
    }


    public void requestData() {
        System.out.println("?????????????????????????????????");
        String textUrl = " http://192.168.0.117:8081/showSpecInfos?key=" + key;
        HttpUtil.sendOkHttpRequest(textUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    System.out.println("????????????????????????????????? aaaa");
                    commentsList = generateTestData();
                    initExpandableListView(commentsList);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("????????????????????????????????? bbb");
                String responseText = response.body().string();
                //线程回到主线程，否则系统交出现错调
                runOnUiThread(() -> {
                    if (responseText != null) {
                        Gson gson = new Gson();
                        CommentBean commentBean = gson.fromJson(responseText, CommentBean.class);
                        commentsList = commentBean.getData().getList();
                        initExpandableListView(commentsList);
                    } else {
                        commentsList = generateTestData();
                        initExpandableListView(commentsList);
                        Toast.makeText(DetailActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    /**
     * 初始化评论和回复列表
     */
    private void initExpandableListView(final List<CommentDetailBean> commentList) {
        expandableListView.setGroupIndicator(null);
        // 设置适配器
        adapter = new CommentExpandAdapter(this, commentList);
        expandableListView.setAdapter(adapter);
        // 设置默认展开
        for (int i = 0; i < commentList.size(); i++) {
            expandableListView.expandGroup(i);
        }
        // 设计父视图的点击事件
        expandableListView.setOnGroupClickListener((expandableListView, view, groupPosition, l) -> {
            boolean isExpanded = expandableListView.isGroupExpanded(groupPosition);
            Log.e(TAG, "onGroupClick: 当前的评论id>>>" + commentList.get(groupPosition).getId());
//            if (isExpanded) {
//                expandableListView.collapseGroup(groupPosition);
//            } else {
//                expandableListView.expandGroup(groupPosition, true);
//            }
            showReplyDialog(groupPosition);
            return true;
        });

        //子视图的点击事件
        expandableListView.setOnChildClickListener((expandableListView, view, groupPosition, childPosition, l) -> {

            if (commentList.get(groupPosition).getReplyList().get(childPosition).getNickName().equals("小红")) {
                showReplyDialog(groupPosition);
            } else {
                showReplyDialog(groupPosition, childPosition);
            }
            return false;
        });

        // 视图展开
        expandableListView.setOnGroupExpandListener(groupPosition -> Log.e("expand", "展开第" + groupPosition + "个分组"));

        // 视图折叠
        expandableListView.setOnGroupCollapseListener(groupPosition -> Log.e("collapse", "折叠第" + groupPosition + "个分组"));
    }

    /**
     * func:生成测试数据
     *
     * @return 评论数据
     */
    private List<CommentDetailBean> generateTestData() {

        CommentBean commentBean;
        try {
            InputStream inputStream = getAssets().open("rep.json");
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            Gson gson = new Gson();
            commentBean = gson.fromJson(inputStreamReader, CommentBean.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return commentBean.getData().getList();
    }

    // 可以设置返回的按钮
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        // 点击评论按钮
        if (view.getId() == R.id.detail_page_do_comment) {

            showCommentDialog();
        }
    }

    /**
     * func:弹出评论框，给发布评论者评论
     */
    private void showCommentDialog() {
        // 初始化
        dialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);

        final EditText commentText = commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = commentView.findViewById(R.id.dialog_comment_bt);
        dialog.setContentView(commentView);
        /*
          解决bsd显示不全的情况
         */
        View parent = (View) commentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        commentView.measure(0, 0);
        behavior.setPeekHeight(commentView.getMeasuredHeight());

        bt_comment.setOnClickListener(view -> {
            String commentContent = commentText.getText().toString().trim();
            if (!TextUtils.isEmpty(commentContent)) {
                // 关掉dialog
                dialog.dismiss();

                // 把评论数据插入
                CommentDetailBean detailBean = new CommentDetailBean("小明", commentContent, "刚刚");
                detailBean.setUserLogo(null);
                adapter.addTheCommentData(detailBean);
//                Toast.makeText(DetailActivity.this, "评论成功", Toast.LENGTH_SHORT).show();


                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("评论成功");
                toast.show();

            } else {
//                Toast.makeText(DetailActivity.this, "评论内容不能为空", Toast.LENGTH_SHORT).show();


                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("评论内容不能为空");
                toast.show();

            }
        });

        // 添加
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        dialog.show();
    }

    /**
     * func:弹出回复框
     */
    private void showReplyDialog(final int position) {
        dialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);

        final EditText commentText = commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = commentView.findViewById(R.id.dialog_comment_bt);

        commentText.setHint("回复 " + commentsList.get(position).getNickName() + " 的评论:");
        dialog.setContentView(commentView);

        bt_comment.setOnClickListener(view -> {
            String replyContent = commentText.getText().toString().trim();
            if (!TextUtils.isEmpty(replyContent)) {
                dialog.dismiss();

                // 把回复数据插入
                ReplyDetailBean detailBean = new ReplyDetailBean("小红", replyContent);

                adapter.addTheReplyData(detailBean, position);

                expandableListView.expandGroup(position);
//                Toast.makeText(DetailActivity.this, "回复成功", Toast.LENGTH_SHORT).show();
                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("回复成功");
                toast.show();

            } else {
//                Toast.makeText(DetailActivity.this, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("回复内容不能为空");
                toast.show();
            }
        });

        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        dialog.show();
    }

    /**
     * func:弹出回复框，给评论者评论
     */
    private void showReplyDialog(final int position, final int childPosition) {
        dialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);

        final EditText commentText = commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = commentView.findViewById(R.id.dialog_comment_bt);

        commentText.setHint("@ " + commentsList.get(position).getReplyList().get(childPosition).getNickName() + " :");
        dialog.setContentView(commentView);

        bt_comment.setOnClickListener(view -> {
            String replyContent = "@" + commentsList.get(position).getReplyList().get(childPosition).getNickName() + " " + commentText.getText().toString().trim();
            if (!TextUtils.isEmpty(replyContent)) {
                dialog.dismiss();

                // 把回复数据插入
                ReplyDetailBean detailBean = new ReplyDetailBean("小明", replyContent);
                adapter.addTheReplyData(detailBean, position);

                expandableListView.expandGroup(position);
//                Toast.makeText(DetailActivity.this, "回复成功", Toast.LENGTH_SHORT).show();
                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("回复成功");
                toast.show();
            } else {
//                Toast.makeText(DetailActivity.this, "回复内容不能为空", Toast.LENGTH_SHORT).show();

                Toast toast = Toast.makeText(DetailActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("回复内容不能为空");
                toast.show();
            }
        });

        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        dialog.show();
    }
}
